package vip.lsjscl.flowboot.util.lock;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

@Aspect
@Component
public class DistributedLockAspect {
    @Autowired
    private RedisDistributedLockService distributedLockService;
    private final ParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();
    private final ExpressionParser parser = new SpelExpressionParser();

    @Around("@annotation(distributedLock)")
    public Object around(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable {
        String lockKey = resolveKey(distributedLock.key(), joinPoint);
        boolean locked = false;
        try { /* 尝试获取锁 */
            locked = tryLock(lockKey, distributedLock);
            if (!locked) throw new RuntimeException(distributedLock.errorMsg());
            return joinPoint.proceed();
        }
        finally {
            if (locked) distributedLockService.unlock(lockKey);
        }
    }

    private boolean tryLock(String lockKey, DistributedLock distributedLock) {
        int retryTimes = distributedLock.retryTimes();
        do {
            boolean locked = distributedLockService.tryLock(lockKey, distributedLock.expire(), distributedLock.timeUnit());
            if (locked || retryTimes == 0) {
                return locked;
            }
            try {
                Thread.sleep(distributedLock.retryInterval());
            }
            catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        } while (retryTimes-- > 0);
        return false;
    }

    private String resolveKey(String key, ProceedingJoinPoint joinPoint) {
        if (!StringUtils.isEmpty(key)) {
            Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            Object[] args = joinPoint.getArgs();
            EvaluationContext context = new MethodBasedEvaluationContext(null, method, args, nameDiscoverer);
            Expression expression = parser.parseExpression(key);
            return expression.getValue(context, String.class);
        }
        return key;
    }
}